﻿using Microsoft.Extensions.Options;

namespace K9Nano.Updater.Pipes;

public class CheckVersionPipe : UpdatePipeBase
{
    public CheckVersionPipe()
    {
        PipeName = "检测版本";
    }

    protected override async Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        var version = context.GetService<IOptions<UpdaterOptions>>().Value.Version;
        context.CurrentVersion = new Version(version);

        var client = context.GetService<IUpdateClient>();

        var availableVersion = await client.GetLatestVersionAsync(cancellation);

        context.TargetVersion = availableVersion?.Version;

        if (context.TargetVersion == null)
        {
            context.LogError("无法获取最新版本");
            context.Terminated = true;
            return;
        }

        context.LogInformation("获取到最新版本：{version}", context.TargetVersion);

        if (context.TargetVersion <= context.CurrentVersion)
        {
            context.LogInformation("当前版本已是最新版本，无需更新");
            context.Terminated = true;
            return;
        }
    }
}
